<?php
namespace app\common\model;
use think\Db;
use think\Model;
use fast\Random;
/**
 * 会员模型
 */
class MemberLogin Extends Model
{
    protected $pk = 'itemid';
    // 表名
    protected $name = 'memberlogin';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = ['url',];

    public function memberinfo(){
  		return $this->hasOne('MemberInfo','memberid','itemid');
  	}
    public function membergroup(){
        return $this->belongsTo('MemberGroup','groupid', 'itemid');
    }
    
    /**
     * 获取个人URL
     * @param   string  $value
     * @param   array   $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['itemid'];
    }

    /**
     * 获取头像
     * @param   string    $value
     * @param   array     $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        return $value ? $value : '/assets/img/avatar.png';
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param   string    $value
     * @param   array     $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array) json_decode($value, TRUE));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object) $value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员积分
     * @param int $score    积分
     * @param int $user_id  会员ID
     * @param string $memo  备注
     */
    public static function score($score, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user)
        {
            $before = $user->score;
            $after = $user->score + $score;
            $level = self::nextlevel($after);
            //更新会员信息
            $user->save(['score' => $after, 'level' => $level]);
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value)
        {
            if ($score >= $value)
            {
                $level = $key;
            }
        }
        return $level;
    }
    /**
     * 根据手机号获取用户资料
     * @param string $mobile 手机号
     * @return array()
     */
    public function getByMobile($mobile = ''){
        $item = $this->where('mobile',$mobile)->find();
        return $item;
    }
    /**
     * 根据用户名获取用户资料
     * @param string $mobile 手机号
     * @return array()
     */
    public function getByUsername($username = ''){
        $item = $this->where('username',$username)->find();
        return $item;
    }
    /**
     * 根据邮箱获取用户资料
     * @param string $email 邮箱
     * @return array()
     */
    public function getByEmail($email = ''){
        $item = $this->where('email',$email)->find();
        return $item;
    }
    /**
     * 根据验证码获取用户资料
     * @param string $email 邮箱
     * @return array()
     */
    public function getByInviteCode($invitecode = ''){
        $item = $this->where('invitecode',$invitecode)->find();
        return $item;
    }
    /**
     * 注册用户
     * @param string $username  用户名
     * @param string $password  密码
     * @param string $email     邮箱
     * @param string $mobile    手机号
     * @param array $extend    扩展参数
     * @return boolean
     */
    public function register($params)
    {
        //$ip = request()->ip();
        $time = time();
        $params['password'] = md5(md5($params['password']) . $params['salt']);
        //$params = array_merge($params, $extend);

        ////////////////同步到Ucenter////////////////
        if (defined('UC_STATUS') && UC_STATUS)
        {
            /*
            $uc = new \addons\ucenter\library\client\Client();
            $user_id = $uc->uc_user_register($username, $password, $email);
            // 如果小于0则说明发生错误
            if ($user_id <= 0)
            {
                $this->setError($user_id > -4 ? 'Username is incorrect' : 'Email is incorrect');
                return 0;
            }
            else
            {
                $params['id'] = $user_id;
            }
            */
        }

        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try
        {
            $member = MemberLogin::create($params);
            $paras = array();
            $paras['memberid'] = $member->itemid;
            $paras['mobile'] = $member->mobile;
            $memberinfo = MemberInfo::create($paras);
            Db::commit();

            // 此时的Model中只包含部分数据
            //$this->_user = MemberLogin::get($user->itemid);
     

            return $member->itemid;
        }
        catch (Exception $e)
        {
            //$this->setError($e->getMessage());
            Db::rollback();
            return 0;
        }
    }
}
